package com.servlet;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.bean.EmployeeBean;
import com.exception.LMSException;
import com.interfaces.EmployeeManager;
import com.manager.EmployeeManagerImpl;

/**
 * Servlet implementation class LoginServlet.
 * 
 * @author : gbs02399 Created on : Jul 6, 2012 Project : LMS File Name :
 *         LoginServlet.java
 */
public class LoginServlet extends HttpServlet {

	/** The Constant serialVersionUID. */
	private static final long serialVersionUID = 1L;

	/**
	 * Instantiates a new login servlet.
	 * 
	 * @see HttpServlet#HttpServlet()
	 */
	public LoginServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * Do post.
	 * 
	 * @param request
	 *            the request
	 * @param response
	 *            the response
	 * @throws ServletException
	 *             the servlet exception
	 * @throws IOException
	 *             Signals that an I/O exception has occurred.
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	@Override
	protected void doPost(final HttpServletRequest request,
			final HttpServletResponse response) throws ServletException,
			IOException {
		final String userID = request.getParameter("userid");
		final String password = request.getParameter("password");
		System.out.println(userID + password);
		final EmployeeManager employeeManager = new EmployeeManagerImpl();
		request.getSession().setAttribute("userid", userID);
		try {
			final EmployeeBean bean = employeeManager.getEmployee(userID,
					password);
			if (bean != null) {
				request.getSession().setAttribute("empRole", bean.getEmpRole());
				final RequestDispatcher loginValidationRequestDispatcher = getServletContext()
						.getRequestDispatcher("/Menu.jsp");
				loginValidationRequestDispatcher.forward(request, response);
			} else {
				request.setAttribute("error", " Invalid Credintials");
				final RequestDispatcher loginValidationRequestDispatcher = getServletContext()
						.getRequestDispatcher("/Login.jsp");
				loginValidationRequestDispatcher.forward(request, response);
			}
		} catch (final LMSException e) {
			request.setAttribute("error", " Invalid Credintials");
			final RequestDispatcher loginValidationRequestDispatcher = getServletContext()
					.getRequestDispatcher("/Login.jsp");
			loginValidationRequestDispatcher.forward(request, response);
		}

	}
}